package com.jeff.android.lab.android.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jeff.utils.LogUtil;

/**
 * @author: dingfeng
 * @date: 2020-02-17
 * @since: 1.0.0
 **/
public class MessengerService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    private Messenger mMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            Bundle bundle = msg.getData();
            String clientMsg = bundle.getString("client");
            LogUtil.d("dingfeng", "Data from client:" + clientMsg);

            try {
                // 模拟耗时操作
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Message message = Message.obtain();
            Bundle reply = new Bundle();
            reply.putString("server", "今天就不去了，还有很多东西要学!!");
            message.setData(reply);

            try {
                msg.replyTo.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    });

}
